<?php

	/**
	 * 购买
	 *
	 *
	 *
	 *
	 */
	class member_buyControl extends mobileMemberControl {

		public function __construct() {
			parent::__construct();
		}

		/**
		 * 购物车、直接购买第一步:选择收获地址和配置方式
		 */
		public function buy_step1Op() {
			$cart_id = explode(',', $_POST['cart_id']);

			$logic_buy = logic('buy');

			//得到购买数据
			$result = $logic_buy->buyStep1($cart_id, $_POST['ifcart'], $this->member_info['member_id'], $this->member_info['store_id']);

			if (!$result['state']) {
				output_error($result['msg']);
			}
			else {
				$result = $result['data'];

				foreach ($result['store_cart_list'] as $key => &$cart_list) {

					foreach($cart_list as $k => &$v){
						$ginfo = ml('goods')->find($v['goods_id']);
						$v['goods_image_url'] = cthumb($v['goods_image'],240,$ginfo['store_id']);
					}

					$tax = cal_tax($cart_list);
					$total_tax += $tax;
				}
			}

			$config = Model('setting')->getListSetting();

//			$distribute = new Distribute();

			//任何时候，优先拆分一次订单
			foreach ($result['store_cart_list'] as $store_id => &$list) {
				foreach ($list as $k => $g) {

					//分销特殊价格
					if (Distribute::isProxy($this->member_info['member_id'])) {
						$ginfo = ml('goods')->find($g['goods_id']);
						$gminfo = ml('goods_common')->find($ginfo['goods_commonid']);
						if ($gminfo['distribute_price'] > 0) {
							$reduce = $list[$k]['goods_price'] - $gminfo['distribute_price'] ;
							$list[$k]['goods_price'] = $gminfo['distribute_price'];
							$result['store_goods_total'][$store_id] -= $reduce * $list[$k]['goods_num'];
						}
					}

					//微团购的购买处理
					if (!empty($_POST['is_we_groupbuy'])) {
						$info = ml('we_groupbuy')->find($_POST['is_we_groupbuy']);
						if ($info) {
							$r = $list[$k]['goods_price'] - $info['price'];
							$list[$k]['goods_price'] = $info['price'] / $info['min_count'];
//							$result['store_goods_total'][$store_id] -= $r * $list[$k]['goods_num'];
							$result['store_goods_total'][$store_id] = $info['price'];
						}
//                    file_put_contents('log', print_r($list, true));
					}


				}


				$no_tax_order = array_filter($list, function ($item) {
					return $item['open_tax'] == 0;
				});
				$tax_order = array_filter($list, function ($item) {
					return $item['open_tax'] == 1;
				});

				//拷贝一份备用
				$_tax_order = $tax_order;
				//统一接口
				if (count($tax_order)) {
					$tax_order = array($tax_order);
				}
				else {
					$tax_order = array();
				}

				//如果组织需要，再拆分一次订单
				if (order_can_split() && count($tax_order)) {
					$total_tax = 0;
					$total_price = 0;
					array_filter($tax_order[0], function ($item) use (&$total_tax, &$total_price) {
						$total_tax += $item['tax'] * $item['goods_num'];
						$total_price += $item['goods_total'];
					});
					//如果触发了拆分条件
					if ($total_tax > $config['split_limit']) {
						$orders = get_split_order($_tax_order);
					}
					else {
						$orders = $tax_order;
					}
					//计算是否触发了免税条件
					cal_free_tax($orders);
					$tax_order = $orders;

				}
				//不拆的话，统一计算一下
				else {
					cal_free_tax($tax_order);
				}


				$goods_total = &$result['store_goods_total'][$store_id];

				foreach ($no_tax_order as $goods) {
					$goods_total = $goods_total - ($goods['reduce'] - $goods['tax']) * $goods['goods_num'];
				}

				foreach ($tax_order as $orders) {
					foreach ($orders['goods'] as $goods) {
						$goods_total = $goods_total - ($goods['reduce'] - $goods['tax']) * $goods['goods_num'];
					}
				}


				$result['store_cart_list'][$store_id] = array(
					'no_tax_order' => $no_tax_order,
					'tax_order'    => $tax_order,
					'sinfo'        => Model('store')->find($store_id)
				);
			}


			// $GLOBALS['superboy'] = 1;
			// $logic_buy = logic('buy');
			// $result = $logic_buy->buyStep2($_POST, $_SESSION['member_id'], $_SESSION['member_name'], $_SESSION['member_email']);
			// $logic_buy = null;
			// unset($GLOBALS['superboy']);

			// print_r($result);

			$logic_buy = Logic('buy');
			//整理数据
			$store_cart_list = array();
			foreach ($result['store_cart_list'] as $key => $value) {
				$store_cart_list[$key]['goods_list'] = $value;
				$store_cart_list[$key]['store_goods_total'] = $result['store_goods_total'][$key];
				if (!empty($result['store_premiums_list'][$key])) {
					$result['store_premiums_list'][$key][0]['premiums'] = true;
					$result['store_premiums_list'][$key][0]['goods_total'] = 0.00;
					$store_cart_list[$key]['goods_list'][] = $result['store_premiums_list'][$key][0];
				}
				$store_cart_list[$key]['store_mansong_rule_list'] = $result['store_mansong_rule_list'][$key];
				$store_cart_list[$key]['store_voucher_list'] = $result['store_voucher_list'][$key];
				if (!empty($result['cancel_calc_sid_list'][$key])) {
					$store_cart_list[$key]['freight'] = '0';
					$store_cart_list[$key]['freight_message'] = $result['cancel_calc_sid_list'][$key]['desc'];
				}
				else {
					$store_cart_list[$key]['freight'] = '1';
				}
				$store_cart_list[$key]['store_name'] = $value[0]['store_name'];
			}

			$buy_list = array();
			$buy_list['store_cart_list'] = $store_cart_list;
			$buy_list['freight_hash'] = $result['freight_list'];
			$buy_list['address_info'] = $result['address_info'];
			$buy_list['ifshow_offpay'] = $result['ifshow_offpay'];
			$buy_list['vat_hash'] = $result['vat_hash'];
			$buy_list['inv_info'] = $result['inv_info'];
			$buy_list['available_predeposit'] = $result['available_predeposit'];
			$buy_list['available_rc_balance'] = $result['available_rc_balance'];
			output_data($buy_list, array(), 'logwechat');
		}

		/**
		 * 购物车、直接购买第二步:保存订单入库，产生订单号，开始选择支付方式
		 *
		 */
		public function buy_step2Op() {

			$param = array();
			$param['ifcart'] = $_POST['ifcart'];
			$param['cart_id'] = explode(',', $_POST['cart_id']);
			$param['address_id'] = $_POST['address_id'];
			$param['vat_hash'] = $_POST['vat_hash'];
			$param['offpay_hash'] = $_POST['offpay_hash'];
			$param['offpay_hash_batch'] = $_POST['offpay_hash_batch'];
			$param['pay_name'] = $_POST['pay_name'];
			$param['invoice_id'] = $_POST['invoice_id'];
			//处理代金券
			$voucher = array();
			$post_voucher = explode(',', $_POST['voucher']);
			if (!empty($post_voucher)) {
				foreach ($post_voucher as $value) {
					list($voucher_t_id, $store_id, $voucher_price) = explode('|', $value);
					$voucher[$store_id] = $value;
				}
			}
			$param['voucher'] = $voucher;

			//手机端暂时不做支付留言，页面内容太多了
			//$param['pay_message'] = json_decode($_POST['pay_message']);
			$param['pd_pay'] = $_POST['pd_pay'];
			$param['rcb_pay'] = $_POST['rcb_pay'];
			$param['password'] = $_POST['password'];
			$param['fcode'] = $_POST['fcode'];
			$param['order_from'] = 2;
			if ($_POST['is_we_groupbuy']) {
				$param['is_we_groupbuy'] = $_POST['is_we_groupbuy'];
			}


			$m = Model('setting');
			$config = $m->getListSetting();
			$tax_start = $config['tax_start_else'];
			$tax_top = $config['tax_start'];

			//任何时候，优先拆分一次订单
			$GLOBALS['superboy'] = 1;
			$GLOBALS['FIRST_SPLIT'] = 1;
			$logic_buy = logic('buy');
			$result = $logic_buy->buyStep2($param, $this->member_info['member_id'], $this->member_info['member_name'], $this->member_info['member_email']);
			if (!$result['state'] && $result['msg']) {
				output_error($result['msg']);
			}
			$logic_buy = null;
			unset($GLOBALS['superboy']);
			unset($GLOBALS['FIRST_SPLIT']);

			$flag = 0;

			// print_r($result);uy_goods_list
			foreach ($result as $key => $val) {
				$goods = $val['_goods'];
				foreach ($goods as $g) {
					if ($g['open_tax'] == 1) {
						$flag++;
					}
				}
			}


			if ($flag) {
				// $user = Model('member')->find($this->member_info['member_id']);
				// if(empty($user['idcard'])){
				//     output_error('您还未填写身份证信息<br>无法购买保税商品！');
				//     exit;
				// }
				// if(empty($user['zpic']) || empty($user['fpic'])){
				//     output_error('您还未上传身份证正反面图片<br>无法购买保税商品！');
				//     exit;
				// }
			}


			#订单拆分开启的情况，再拆第二次订单
			if (order_can_split() && $flag) {
				$GLOBALS['superboy'] = 1;
				$logic_buy = logic('buy');
				$result = $logic_buy->buyStep2($param, $this->member_info['member_id'], $this->member_info['member_name'], $this->member_info['member_email']);
				$logic_buy = null;
				unset($GLOBALS['superboy']);
			}


			#只要有保税商品，就计算数量
			if ($flag) {
				$model_setting = Model('setting');
				$config = $model_setting->getListSetting();
				if ($config['buyer_limit'] == 1) {
					$copy = $result;
					$copy = array_filter($copy, function ($item) {
						if ($item['_goods'][0]['open_tax'] == 1) {
							return true;
						}
						return false;
					});
					$count = count($copy);

					list($today_orders, $week_orders, $month_orders, $year_orders, $last_order_time) = $ret = get_order_count($this->member_info['member_id'], $param['address_id']);
					$limit = array(
						'day'   => 2,
						'week'  => 5,
						'month' => 10
					);

					if ($config['custom_interface'] == 'hangzhou') {

						if ($count + $today_orders['num'] > $limit['day']) {
							output_error("您今天已达到保税订单个数提交上限（2单）<br>无法再提交新的订单！");
						}
						if ($count + $week_orders['num'] > $limit['week']) {
							output_error("您本周已达到保税订单个数提交上限（5单）<br>无法再提交新的订单！");
						}
						if ($count + $month_orders['num'] > $limit['month']) {
							output_error("您本月已达到保税订单个数提交上限（5单）<br>无法再提交新的订单！");
						}

						if ($year_orders['total'] > 20000) {
							output_error("您本年已达到保税订单金额上限（20000元）<br>无法再提交新的订单！");
						}

						if (time() - $last_order_time < 600) {
							output_error('保税订单的最小下单间隔为10分钟！');
						}
					}

				}

			}


			// print_r($result);

			if ((order_can_split() || $flag)) {

				$logic_buy = logic('buy');

				foreach ($result as $key => $val) {
					$m = Model('cart');
					$goods = $val['_goods'];
					$cart = array();
					$tax = 0;
					$total = 0;
					foreach ($goods as $g) {
						if (isset($g['tax']) && $g['tax'] > 0) {
							$tax += $g['tax'];
							$total += $g['goods_price'] * $g['goods_num'];
						}
					}

					if ($tax < $tax_start && $total < $tax_top) {
						foreach ($goods as $k => $g) {
							if (isset($g['tax']) && $g['tax'] > 0) {
								// $g['goods_price'] -= $g['tax'];
								$$goods[$k]['tax'] = 0;
							}
						}
					}

					$newcart = array();

					foreach ($goods as $g) {
						unset($g['cart_id']);
						$fields = array(
							'cart_id',
							'buyer_id',
							'store_id',
							'store_name',
							'goods_id',
							'goods_name',
							'goods_price',
							'goods_num',
							'goods_image',
							'bl_id'
						);
						if (isset($g['source_price']) && $g['source_price'] != $g['goods_price']) {
							$g['goods_price'] = $g['source_price'];
						}
						foreach ($g as $k => $v) {
							if (!in_array($k, $fields)) {
								unset($g[$k]);
							}
						}
						unset($g['cart_id']);
						$cid = $m->insert($g);
						if ($cid && $param['ifcart']) {
							$cart[] = $cid . '|' . $g['goods_num'];
							$newcart[] = $cid;
						}else{
							$cart[] = $g['goods_id'] . '|' . $g['goods_num'];
							$newcart[] = $cid;
						}
					}
					$param['cart_id'] = $cart;
					$result = $logic_buy->buyStep2($param, $this->member_info['member_id'], $this->member_info['member_name'], $this->member_info['member_email']);
					if (!$result['state']) {
						output_error($result['msg']);
					}
					else {
						if (count($newcart)) {
							$m = Model('cart');
							$m->where(array(
								'cart_id' => array(
									'in',
									$newcart
								)
							))->delete();
						}
					}


				}


				if ($result['state']) {
					//清空购物车
					$m = Model('cart');
					$m->where(array('buyer_id' => $this->member_info['member_id']))->delete();
					output_error("订单自动拆分成功<br>请到订单中心完成后续支付");
				}

			}
			else {
				$logic_buy = logic('buy');

				$result = $logic_buy->buyStep2($param, $this->member_info['member_id'], $this->member_info['member_name'], $this->member_info['member_email']);


				if (!$result['state']) {
					output_error($result['msg']);
				}

				output_data(array('pay_sn' => $result['data']['pay_sn']));
			}


		}

		/**
		 * 验证密码
		 */
		public function check_passwordOp() {
			if (empty($_POST['password'])) {
				output_error('参数错误');
			}

			$model_member = Model('member');
			$member_info = $model_member->getMemberInfoByID($this->member_info['member_id']);
			if ($member_info['member_paypwd'] == md5($_POST['password'])) {
				output_data('1');
			}
			else {
				output_error('密码错误');
			}
		}

		/**
		 * 更换收货地址
		 */
		public function change_addressOp() {
			$logic_buy = Logic('buy');

			$data = $logic_buy->changeAddr($_POST['freight_hash'], $_POST['city_id'], $_POST['area_id'], $this->member_info['member_id']);
			if (!empty($data) && $data['state'] == 'success') {
				output_data($data);
			}
			else {
				output_error('地址修改失败');
			}
		}


	}

